package com.ruoyi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.PageResult;
import com.ruoyi.common.Result;
import com.ruoyi.common.config.FileStorageProperties;
import com.ruoyi.common.exception.FileErrorException;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.domain.Templates;
import com.ruoyi.domain.TemplatesDTO;
import com.ruoyi.domain.TemplatesVO;
import com.ruoyi.mapper.TemplatesMapper;
import com.ruoyi.service.TemplatesService;
import com.ruoyi.thread.thread;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @Classname TemplatesServiceImpl
 * @Description TODO
 * @Date 2025/3/20 09:48
 * @Created by xxx
 */
@Slf4j
@Service
@Data
@RequiredArgsConstructor
public class TemplatesServiceImpl implements TemplatesService {
    private final FileStorageProperties fileStorageProperties;
    private final TemplatesMapper templatesMapper;
    private ThreadPoolTaskExecutor executor = SpringUtils.getBean("threadPoolTaskExecutor");

    private String getBaseUrl() {
        //获取当前ip和端口
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String baseUrl = "http://" + address.getHostAddress() + ":" + fileStorageProperties.getUsePort();
        return baseUrl;
    }

    @Override
    public boolean upload(TemplatesDTO templatesDTO) {
        Long createBy = templatesDTO.getCreateBy();
        String title = templatesDTO.getTitle();
        MultipartFile file = templatesDTO.getFile();
        Path saveDir = Paths.get(fileStorageProperties.getTemplateDir(), String.valueOf(createBy));
        //String url = fileStorageProperties.getLocalResources();
        //获取当前ip和端口
        String baseUrl = getBaseUrl();
        String url = "/templates/" + String.valueOf(createBy);
        UUID uuid = UUID.randomUUID();
        Path savePath = saveDir.resolve(uuid.toString() + "." + file.getOriginalFilename().split("\\.")[1]);
        url += "/" + uuid.toString() + "." + file.getOriginalFilename().split("\\.")[1];
        try {
            Files.createDirectories(saveDir);
        } catch (IOException e) {
            throw new FileErrorException("创建目录失败");
        }
        try {
            file.transferTo(savePath);
        } catch (IOException e) {
            throw new FileErrorException("上传文件失败");
        }
//        http://127.0.0.1:8012/onlinePreview?
//       url = "http://" + getFileStorageProperties().getOnlineUrl() + "/onlinePreview?url=" + url;
        log.info("模板url:{}", url);
        Path imageDir = Paths.get(fileStorageProperties.getTemplateDir(), String.valueOf(createBy), uuid.toString());
        Templates templates = Templates.builder()
                .title(title)
                .filePath(savePath.toString())
                .createBy(createBy)
                .createTime(LocalDateTime.now())
                .url(url)
                .build();
        templatesMapper.insert(templates);
        //new Thread(new thread(templates.getId(), savePath, imageDir, fileStorageProperties, templatesMapper)).start();
        executor.execute(new thread(templates.getId(), savePath, imageDir, fileStorageProperties, templatesMapper));
        return true;
    }

    @Override
    public PageResult list(TemplatesDTO templatesDTO) {
        PageHelper.startPage(templatesDTO.getPage(), templatesDTO.getPageSize());
        Templates templates = Templates.builder()
                .title(templatesDTO.getTitle())
                .createBy(templatesDTO.getCreateBy())
                .build();
        List<TemplatesVO> templatesVOS = templatesMapper.list(templates);
        PageInfo<TemplatesVO> pageInfo = new PageInfo<>(templatesVOS);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public boolean delete(Integer id, Long userId) {
        Templates templates = Templates.builder()
                .id(id)
                .createBy(userId).build();
        Templates templates1 = templatesMapper.selectById(templates);
        templatesMapper.deleteById(templates);
        Path filePath = Paths.get(templates1.getFilePath());
        Path imageDir = Paths.get(templates1.getImageDir());
        try {
            if (Files.exists(filePath)) Files.delete(filePath);
            if (Files.exists(imageDir)) Files.delete(imageDir);
        } catch (IOException e) {
            throw new FileErrorException("删除文件失败");
        }
        return true;
    }


    @Override
    public Templates getDownloadPath(Integer templateId, Long userId) {
        Templates templates = Templates.builder()
                .id(templateId)
                .createBy(userId).build();
        Templates templates1 = templatesMapper.selectById(templates);
        return templates1;
    }

    @Override
    public Result listAll() {
        List<Templates> templatesList = templatesMapper.listAll();
        return Result.success(templatesList);
    }
}
